package network.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

class NetClient {

	private Socket socket = null;
	private ObjectOutputStream writer = null;
	private ObjectInputStream reader = null;
	
	private Output output;
	private ClientInputThread input;
	
	private String serverName;
	private int port;
	
	public NetClient(String serverName, int port) {
		this.serverName = serverName;
		this.port = port;
	}
	
	public void setServer(String serverName) {
		this.serverName = serverName;
	}
	
	public void setPort(int port) {
		this.port = port;
	}
	
	public void connect() throws ConnectionFailedException, UnknownHostException {
		try {
			socket = new Socket(serverName, port);
			OutputStream outputStream = socket.getOutputStream();
	    	InputStream inputStream = socket.getInputStream();
	    	
	    	writer = new ObjectOutputStream(outputStream);
	    	
			reader = new ObjectInputStream(inputStream);
			
			output = new Output(writer);
			
			input = new ClientInputThread(reader);
			input.start();
			
		} catch (UnknownHostException e1) {
			System.out.println("UNKNOWNHOSTEXCEPTION!");
			// TODO Auto-generated catch block
			//e1.printStackTrace();
			throw e1;
			
		} catch (IOException e1) {
			//TODO: Remove println
			System.out.println("IOEXCEPTION!");
			throw new ConnectionFailedException();
		}
	}
	
	public void send(Object obj) {
		output.send(obj);
	}
	
	public void addNetworkListener(ClientNetworkListener listener) {
		input.addNetworkListener(listener);
	}
	
	public void addClientInputThreadListener(ClientInputThreadListener listener) {
		input.addInputThreadListener(listener);
	}
	
	public void shutDown() {
		try {
			writer.close();
			reader.close();
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
